<template>
  <div class="login-box">
    <div class="header">
      <h3 class="brand">
        情报魔方
        <span>专业数据平台</span>
      </h3>
    </div>
    <div class="login-bg"></div>
    <div class="login-centent" :style="right">
      <h3 class="welcome">忘记密码</h3>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="0px"
        class="login-form"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="ruleForm.phone"
            prefix-icon="candy-icon-user"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="imageCode">
          <el-row :gutter="10">
            <el-col :span="13">
              <el-input
                v-model="ruleForm.imageCode"
                prefix-icon="candy-icon-phone"
                placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col :span="11">
              <el-button
                type="dark"
                class="phoneCode"
                @click="getCode"
                :disabled="buttonDisable"
                >{{ buttonText }}</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            prefix-icon="candy-icon-password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <div class="error-box">{{ errorText }}</div>
        <el-form-item style="margin-bottom:0;">
          <el-button type="dark" class="block" @click="submitForm('ruleForm')"
            >确认重置</el-button
          >
        </el-form-item>
        <el-form-item class="clearfix info">
          <a class="right forget" href="javascript:;" @click="login">去登录</a>
        </el-form-item>
      </el-form>
    </div>

    <div class="footer">
      © Copyright © 2018 糖豆兄弟（北京）科技有限公司 京ICP备17042143号-3
    </div>
  </div>
</template>
<script>
import md5 from 'js-md5';
import { mapActions } from 'vuex';

export default {
  name: 'Login',
  data() {
    return {
      errorText: '',
      buttonText: '获取验证码',
      timeLimit: 60,
      buttonDisable: false,
      ruleForm: {
        uuid: '',
        phone: '',
        password: '',
        imageCode: '',
        remember: false
      },
      rules: {
        phone: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码'
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        imageCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      timeFn: null
    };
  },
  computed: {
    right() {
      return { right: (document.body.clientWidth / 1920) * 332 + 'px' };
    }
  },
  methods: {
    ...mapActions({
      storeUser: 'user/storeUser'
    }),
    /**
     * 重置密码
     */
    async resetPassword() {
      this.errorText = '';
      const params = {
        phone: this.ruleForm.phone,
        password: md5(this.ruleForm.password),
        code: this.ruleForm.imageCode
      };

      const res = await this.$http.post(
        { map: 'LOGIN', url: 'resetPassword' },
        params
      );

      console.log(res);

      // 保存token
      const token =
        res['headers']['x-authtoken'] || res['headers']['X-AuthToken'] || null;
      window.localStorage.setItem('token', token);
      this.$http.setHeaders({ 'x-authtoken': token });

      const { data } = res;

      if (data['success']) {
        this.$message({
          type: 'success',
          message: '密码重置成功'
        });
        this.$refs['ruleForm'].resetFields();

        setTimeout(() => {
          this.$router.push({ name: 'login' });
        }, 300);
      } else {
        this.$message({
          type: 'error',
          message: data['msg']
        });
      }
    },
    /**
     * 获取验证码
     */
    getCode() {
      // console.log(this.$refs['ruleForm']);
      this.$refs['ruleForm'].validateField('phone');
      if (this.$refs['ruleForm'].fields[0]['validateState'] === 'error') {
        return;
      }

      this.buttonDisable = true;
      this.buttonText = '60秒...';
      this.$http
        .post(
          { map: 'LOGIN', url: 'sendVerifySMS' },
          { phone: this.ruleForm.phone }
        )
        .then()
        .catch(err => {
          this.$message({
            type: 'error',
            message: err['msg']
          });
        });
      this.time();
    },
    /**
     * 倒计时
     */
    time() {
      this.timeFn = setTimeout(() => {
        this.timeLimit -= 1;
        if (this.timeLimit > 0) {
          this.buttonText = this.timeLimit + '秒...';
          this.time();
        } else {
          this.buttonText = '获取验证码';
          this.timeLimit = 60;
          this.buttonDisable = false;
        }
      }, 1000);
    },

    /**
     * 表单提交
     */
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // this.$router.push('home');
          this.resetPassword();
          return false;
        }
        return false;
      });
    },

    /**
     * 忘记密码
     */
    login() {
      this.$router.push({ name: 'login' });
    }
  },
  beforeDestroy() {
    if (this.timeFn) {
      clearTimeout(this.timeFn);
    }
  }
};
</script>

<style lang="less"></style>
